package com.xiyoukt.springboot.service.impl;

import com.xiyoukt.springboot.User;
import com.xiyoukt.springboot.jpa.UserRepository;
import com.xiyoukt.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public List<User> getAll() {
        return userRepository.findAll();
    }

    @Override
    public void delUser(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public List<User> getUser(Integer gender) {
        // 生成匹配器实例
        ExampleMatcher matcher = ExampleMatcher.matching()
//                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.caseSensitive())
                .withMatcher("gender", ExampleMatcher.GenericPropertyMatchers.caseSensitive());
        User user = new User();
        user.setGender(gender);
        Example<User> example = Example.of(user, matcher);
        Sort sort = new Sort(Sort.Direction.DESC, "name");
        Pageable pageable = PageRequest.of(0, 1, sort);
        Page<User> all = userRepository.findAll(example, pageable);
        return all.getContent();
    }

    @Override
    public List<User> getUserByGender(Integer gender) {
        Sort sort = new Sort(Sort.Direction.DESC, "name");
        Pageable pageable = PageRequest.of(0, 1, sort);
        return userRepository.getUserByGender(gender, pageable);
    }

    @Override
    public List<User> findUserByGender(Integer gender) {
        Sort sort = new Sort(Sort.Direction.DESC, "name");
        Pageable pageable = PageRequest.of(0, 1, sort);
        return userRepository.findUserByGender(gender, pageable);
    }
}
